package com.keyinong.caizhengting.view;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.keyinong.caizhengting.R;
import com.keyinong.caizhengting.tools.HttpTools;
import com.keyinong.caizhengting.tools.NetWorkUtil;
import com.keyinong.caizhengting.tools.Utility;
import com.keyinong.caizhengting.adapter.MyteamorderAdapter;
import com.keyinong.caizhengting.entity.MyorderEntity;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * 我的订单(old)
 */

public class WodedingdanFragment extends Fragment {
    /**
     * 获得数据
     */
    ArrayList<MyorderEntity> infolist;
    //	/**是否团队订餐*/
//	String teamorderid;
    HttpTools httptools = null;
    String token = "";
    int offset = 0;
    int page = 3;
    //	private MyorderAdapter myorderAdapter;
    private MyteamorderAdapter myteamorderAdapter;
    /**
     * 订单列表
     */
    private ListView lv;
    /**
     * 刷新
     */
    private PullToRefreshScrollView pull_myorder;
    /**
     * 份数
     */
    private int shuliang;
    /**
     * 总价
     */
    private double zongjia;
    // 上下拉刷新
    private OnRefreshListener2<ScrollView> onrefresh = new OnRefreshListener2<ScrollView>() {

        @Override
        public void onPullDownToRefresh(
                PullToRefreshBase<ScrollView> refreshView) {
            offset = 0;
            infolist.clear();
            //				shuliang=0;
            httptools.myorder(token, page + "", offset + "", 0,
                    new JsonDingdan());
            if (NetWorkUtil.isNetwork(getActivity()) == false) {
                Toast.makeText(getActivity(), "当前网络不可用", Toast.LENGTH_SHORT).show();
                pull_myorder.onRefreshComplete();
                return;
            }
        }

        @Override
        public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
            offset += page;
            //				shuliang=0;
            httptools.myorder(token, page + "", offset + "", 0,
                    new JsonDingdan());
            if (NetWorkUtil.isNetwork(getActivity()) == false) {
                pull_myorder.onRefreshComplete();
                return;
            }

        }

    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_wodedingdan, null);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);
        SharedPreferences sp = getActivity().getSharedPreferences("spReg",
                Context.MODE_PRIVATE);
        token = sp.getString("data", "");
        pull_myorder = (PullToRefreshScrollView) getView().findViewById(R.id.pull_wodedingdan);
        pull_myorder.setMode(Mode.BOTH);
        pull_myorder.setOnRefreshListener(onrefresh);
        lv = (ListView) getView().findViewById(R.id.lv_dingdan);
        Dingdan();
        //		Shuliang();
    }

    //	private void Shuliang() {
    //		infolist=new ArrayList<MyorderEntity>();
    //		if (httptools == null) {
    //			httptools = new HttpTools(getActivity());
    //		}
    //		httptools.myorder(token, ""+page,""+ offset, new JsonShuliang());
    //	}
    //	public class JsonShuliang extends JsonHttpResponseHandler {
    //		@Override
    //		public void onSuccess(int statusCode, Header[] headers,
    //				JSONObject response) {
    //			// TODO Auto-generated method stub
    //			super.onSuccess(statusCode, headers, response);
    //			try {
    //				boolean code = response.getBoolean("code");
    //				String msg = response.getString("msg");
    //				if(code==true){
    //					JSONArray array = response.getJSONArray("data");
    //					for (int i = 0; i < array.length(); i++) {
    //						JSONObject data = array.getJSONObject(i);
    //						JSONArray array2 = data.getJSONArray("details");
    //						for(int j=0;j<array2.length();j++){
    //							JSONObject detail = array2.getJSONObject(j);
    //							String fenshu = detail.getString("amount");
    //							shuliang += Integer.parseInt(fenshu);
    //							Log.i("zq", "shuliang---"+shuliang);
    //							infolist.add(new MyorderEntity(""+shuliang));
    //						}
    //					}
    //				}
    //			} catch (JSONException e) {
    //				e.printStackTrace();
    //			}
    //		}
    //	}
    private void Dingdan() {
        infolist = new ArrayList<MyorderEntity>();

        //		Log.e("shi", "token---" + token);
        if (httptools == null) {
            httptools = new HttpTools(getActivity());
        }
        httptools.myorder(token, "" + page, "" + offset, 0, new JsonDingdan());
    }

    public class JsonDingdan extends JsonHttpResponseHandler {
        @Override
        public void onSuccess(int statusCode, Header[] headers,
                              JSONObject response) {
            // TODO Auto-generated method stub
            super.onSuccess(statusCode, headers, response);
            try {
                boolean code = response.getBoolean("code");
                String msg = response.getString("msg");
                if (code == true) {
                    Log.i("info", response.toString());
                    JSONArray array = response.getJSONArray("data");
                    for (int i = 0; i < array.length(); i++) {
                        JSONObject data = array.getJSONObject(i);
                        String id = data.getString("id");
                        String order_time = data.getString("order_time");
                        String state = data.getString("state");
                        String paymodeid = data.getString("paymodeid");
                        String teamorderid = data.getString("teamorderid");
                        Log.i("zq", "teamorderid---" + teamorderid);
                        JSONArray array2 = data.getJSONArray("details");
                        //						for(int k=0;k<1;k++){
                        //							Log.i("zq", "length1***"+array2.length());
                        if (array2.length() != 0) {
                            JSONObject details = array2.getJSONObject(0);
                            //							Log.i("zq", "details"+details);
                            String name = details.getString("name");
                            String amount = details.getString("amount");
                            String price = details.getString("price");
                            for (int j = 0; j < array2.length(); j++) {
                                JSONObject detail = array2.getJSONObject(j);
                                String fenshu = detail.getString("amount");
                                String jiage = detail.getString("price");
                                zongjia += Integer.parseInt(fenshu) * Double.parseDouble(jiage);
                                Log.i("zq", "zongjia" + zongjia);
                                shuliang += Integer.parseInt(fenshu);
                            }
                            infolist.add(new MyorderEntity(id, state, name, amount, price, order_time, "" + shuliang, "" + zongjia, paymodeid, teamorderid, 0, "0", "0"));
                            zongjia = 0.0;
                            shuliang = 0;
                        }
                    }
                } else {
                    Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
                }
                myteamorderAdapter = new MyteamorderAdapter(getActivity(), infolist, 0);
                lv.setAdapter(myteamorderAdapter);
                lv.setDivider(null);
                Utility.setListViewHeightBasedOnChildren(lv);
                pull_myorder.onRefreshComplete();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
}

